import type { Response } from 'express';
import { rateLimit } from 'express-rate-limit';
const MongoStore = require('rate-limit-mongo');

const n_ms = 5 * 60 * 1000;
const limiter = rateLimit({
	store: new MongoStore({
		uri: process.env.DATA_BASE_URI,
		expireTimeMs: n_ms,
		errorHandler: console.error.bind(null, 'rate-limit-mongo'),
	}),
	limit: 100,
	windowMs: n_ms,
	message: (_req: Request, res: Response) =>
		res.json(
			global.formatResJson({
				code: 'Fail',
				msg: '请求过于频繁~',
			})
		),
});

/**
 * 自定义时间次数限流
 * @param limit   多少次数后开启限制
 * @param second  间隔多长时间后允许再次请求
 */
export const createCustomLimiter = (limit: number, second: number) => {
	// 转换成毫秒
	const n_ms = second * 1000;

	return rateLimit({
		store: new MongoStore({
			uri: process.env.DATA_BASE_URI,
			expireTimeMs: n_ms,
			errorHandler: console.error.bind(null, 'rate-limit-mongo'),
		}),
		limit,
		windowMs: n_ms,
		message: (_req: Request, res: Response) =>
			res.json(
				global.formatResJson({
					code: 'Fail',
					msg: `请求频繁, 请${second}秒后重试`,
				})
			),
	});
};

global.rateLimit = limiter;
export default limiter;
